import { defineStore } from 'pinia'
import { type Ref, nextTick, reactive, ref, watch } from 'vue';
import { Http } from "../model/base/http";
import { MENUTYPE } from '@b/model/enum';

type interfaceMenuAnd = interfaceMenu & { active?: string }

export const loadingStore = defineStore('loading', () => {
  const loading = ref(false)
  const setLoading = (value: boolean) => {
    loading.value = value
  }
  return {
    loading, setLoading
  }
})

export const fullScreenStore = defineStore('fullScreen', () => {
  const WIDTH = 820
  const fullscreen = ref(false)
  const windowWidth = ref(innerWidth)
  const transitionFinish = ref(true)
  const setWindowWidth = (width: number, change?: boolean) => {
    if (!change) return
    windowWidth.value = width
    changefullScreen(width < WIDTH)
  }
  const changefullScreen = (state?: boolean) => {
    if (windowWidth.value < WIDTH) {
      fullscreen.value = true
      return
    }
    if (state === undefined)
      fullscreen.value = !fullscreen.value
    else
      fullscreen.value = state
  }
  return {
    fullscreen, transitionFinish, changefullScreen, setWindowWidth
  }
})

export const adminStore = defineStore('admin', () => {
  const isLogin = ref(false)//确认登录态
  const http = new Http()
  const token = ref(localStorage.getItem('token') || '')
  if (!token.value) {
    isLogin.value = true
  }
  const userInfo: Ref<interfaceUser | undefined> = ref()
  const setuserInfo = async (cache: 'cache' | 'recache' = 'cache') => {
    if (!token.value) return
    userInfo.value = await http.request('/token/userinfo', { method: 'GET', cache })
    return userInfo.value
  }
  const logOut = () => {
    isLogin.value = true
    userInfo.value = undefined
    token.value = ""
    localStorage.removeItem('token')
    localStorage.removeItem('refreshToken')
  }
  const reLogin = async () => {
    const refreshToken = localStorage.getItem('refreshToken')
    if (refreshToken && refreshToken !== 'undefined' && refreshToken !== '') {
      const res = await http.request('/admin/base/open/refreshToken', { method: 'GET', parames: { refreshToken } })
      if (res) {
        localStorage.setItem('token', res.token)
        localStorage.setItem('refreshToken', res.refreshToken)
        token.value = res.token
        return true
      }
    } else {
      logOut()
      return false
    }
  }
  const login = async (data: interfaceLogin) => {
    if (!data.username) return
    const res = await http.request('/token/login', { data })
    localStorage.setItem('phone', data.username)
    if (res) {
      localStorage.setItem('token', res)
      // localStorage.setItem('refreshToken', res.refreshToken)
      token.value = res
      isLogin.value = false
      setuserInfo('recache')
      // location.reload()
      return true
    } else {
      return false
    }
  }
  return { token, isLogin, userInfo, logOut, setuserInfo, reLogin, login }
})

export const pagebuttonStore = defineStore('pagebutton', () => {
  const http = new Http()
  const headActive = ref(0)
  const headActiveRouter = ref('')
  const asideActive = ref(0)
  const childMenu: Ref<interfaceMenu[]> = ref([])
  const menuSelf: Ref<interfaceMenu | null> = ref(null)
  const bread: Ref<interfaceMenu[]> = ref([])
  const button: Map<string, string> = reactive(new Map())
  const clearCache = () => {
    http.cache.clear()
  }
  const setRelationship = async (routerUrl: string) => {
    button.clear()
    const res: interfaceRelationship = await http.request(`/token/routes?routerUrl=${routerUrl}&isPhone=${window.isPhone}`, { method: 'GET', cache: 'cache' })
    if (res) {
      res.childMenu?.forEach((item) => {
        button.set(item.perms, item.name)
      })
      bread.value = res.bread
      asideActive.value = res.asideMenu.id
      headActive.value = res.headerMenu.id
      headActiveRouter.value = res.headerMenu.router
      menuSelf.value = res.self
      childMenu.value = res.childMenu
      return menuSelf.value.name
    }
    return ''
  }
  return { headActive, asideActive, bread, button, childMenu, menuSelf, headActiveRouter, setRelationship, clearCache }
})

export const navBarStore = defineStore('navbar', () => {
  const navbar = ref("标题")
  const background = ref('var(--van-background-2)')
  const color = ref('var(--van-text-color)')
  let titles: string[] = []
  const setBackground = (value: string) => {
    background.value = value
  }
  const setColor = (value: string) => {
    color.value = value
  }
  const setNavBar = (items: string, changeUrl: boolean = true) => {
    if (changeUrl) {
      navbar.value = titles[0] || items
      titles = []
    } else {
      titles = [items]
    }
  }
  return { navbar, background, color, setBackground, setColor, setNavBar }
})

export const headStore = defineStore('head', () => {
  const http = new Http()
  const options: Ref<interfaceMenuAnd[]> = ref([])
  const asideOption: Ref<interfaceMenuAnd[]> = ref([])
  let lastHeadId = 0
  const getMemu = async (cache: 'cache' | 'recache' = 'cache') => {
    options.value = await http.request('/token/menus?isPhone=' + window.isPhone, { method: 'GET', cache, unShowToast: true })
    return options.value
  }
  const getFristPage = (item: interfaceMenuAnd) => {
    const fun = (item: interfaceMenuAnd) => {
      if (!item) return ''
      const children = item.childMenus ? item.childMenus[0] : undefined
      if (item.type == MENUTYPE.菜单) return item.router
      if (children) return fun(children)
      else return item.router
    }
    if (lastHeadId === item.id) item!.active = ''
    return item.active || fun(item)
  }

  const getAsideByPage = async (id: number, url: string | ((item: interfaceMenuAnd) => string | undefined)) => {
    const getUrl = (item: interfaceMenuAnd) => {
      if (typeof url === 'string') {
        return url
      } else {
        return url(item)
      }
    }
    const item = options.value?.find(item => item.id === id)
    if (!item) return
    asideOption.value = item.childMenus || []
    const Url = getUrl(item)
    item.active = Url
    return item
  }

  const getAsideByHead = async (id: number) => {
    const item = await getAsideByPage(id, getFristPage)
    lastHeadId = id
    if (item) return item.active
    else return ''
  }
  return { asideOption, options, getAsideByHead, getAsideByPage, getMemu }
})

export const CheckedListShowStore = defineStore('CheckedListShow', () => {
  const show = ref(false)
  const setShow = async (value: boolean) => {
    show.value = value
    await nextTick()
  }
  return {
    show, setShow
  }
})

export const isDarkStore = defineStore('isDark', () => {
  const isDark = ref(localStorage.getItem('isDark') === 'dark')
  const darkClassName = window.isPhone ? 'van-doc-theme-dark van-theme-dark' : 'dark'
  document.documentElement.className = isDark.value ? darkClassName : ''
  const change = () => {
    localStorage.setItem('isDark', isDark.value ? 'dark' : 'light')
    document.documentElement.className = isDark.value ? darkClassName : ''
  }
  const watchDark = (cb: (isDark: boolean) => void) => {
    watch(isDark, (val) => {
      cb(val)
    })
  }
  return { isDark, change, watchDark }
})

export const isCollapseStore = defineStore('isCollapse', () => {
  const isCollapse = ref(localStorage.getItem('collapse') ? true : false)
  const setCollapse = (value: boolean) => {
    if (value) {
      localStorage.setItem('collapse', 'true')
    } else {
      localStorage.removeItem('collapse')
    }
    isCollapse.value = value
  }
  return { isCollapse, setCollapse }
})